
var tracePath = function(selector, isFirstClassName) {
    return ({
        className: function(selector) {
            var cla = String($(selector).attr('class')).replace(/\s+/g, '.');
            if (isFirstClassName) {
                var spl = cla.split('.');
                if (spl) return spl[0];
            }
            return cla
        },
        idName: function(selector) {
            return $(selector).attr('id')
        },
        tagName: function(selector) {
            return $(selector)[0].tagName.toLowerCase();
        },
        merger: function(selector) {
            var query = '',
            tag, id, cla;
            if (tag = this.tagName(selector)) {
                query += tag;
            }
            if (id = this.idName(selector)) {
                query += '#' + id;
            }
            if ((cla = this.className(selector)) && cla !== 'undefined') {
                query += '.' + cla;
            }
            return query;
        },
        path: function(selector) {
            var querys = this.merger(selector),
            $$ = this;
            $(selector).parents().each(function() {
                var query;
                if ((query = $$.merger(this))) {
                    querys = query + ' > ' + querys;
                }
            });
            return querys;
        }

    }).path(selector);

};
function serialize(object){
    var ret = '';
    for(var n in object){
        ret+= '&'+n+'='+object[n];
    }
    return ret.substr(1);
}
function unSerialize(str){
    var ret = '{';
        ret+= str.replace(/([0-9a-zA-Z\-_]+)=([0-9a-zA-Z\-_\u4E00-\u9FA5]+)/g,'"$1":"$2"').replace(/&/g,',');
        
    ret+='}';
    return JSON.parse(ret);
}
+function($){
	$.ajaxSetup({
	    error:function(x,e){
	        alert("请求出错");
	        return false;
	    }
	});
	
	$.fn.serializeObject=function(multipleToStr){
		multipleToStr=multipleToStr || false;
		var o={};
		var a=this.serializeArray();
		$.each(a,function(){
			if(o[this.name] || o[this.name]==''){
				if(multipleToStr){
					o[this.name]=o[this.name]+','+this.value.trim();
				}else{
					if(!o[this.name].push){
						o[this.name]=[o[this.name]];
					}
					o[this.name].push(this.value.trim() || '');
				}
			}else{
				o[this.name]=this.value.trim() || '';
			}
		});
		return o;
	}
	
	Date.prototype.format = function(format) { //时间戳转换
       var date = {
              "M+": this.getMonth() + 1,
              "d+": this.getDate(),
              "h+": this.getHours(),
              "m+": this.getMinutes(),
              "s+": this.getSeconds(),
              "q+": Math.floor((this.getMonth() + 3) / 3),
              "S+": this.getMilliseconds()
       };
       if (/(y+)/i.test(format)) {
              format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
       }
       for (var k in date) {
              if (new RegExp("(" + k + ")").test(format)) {
                     format = format.replace(RegExp.$1, RegExp.$1.length == 1
                            ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
              }
       }
       return format;
	}
	
	$.isMobileNum = function(mobile){
		if(!mobile) return false;
		if(!(mobile+'').match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[13678]|18[0-9]|14[57])[0-9]{8}$/)){
    		return false;
    	}
		return true;
	}
	$.isTelNum = function(tel){
		if(!tel) return false;
		if(!(tel+'').match(/^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/)){
    		return false;
    	}
		return true;
	}
	
	$.setLocalValue = function(name,value){    
		if(!name) return false;   if(value != 0 && !value)   return false;
		localStorage.setItem(name,escape(value));   
	}
	
	$.getLocalValue = function(name){
		var value = localStorage.getItem(name);
		if(value != 0 && !value){  return ''  }else{  return unescape(value)  } 
	}
	
	$.removeLocalValue = function(name){   localStorage.removeItem(name);   }
	$.removeLocalValueByStartName = function(name,type){   
		var key_count = localStorage.length;
		var checkName = function(val,checkval){
			if(type == 'start') return val.slice(0, checkval.length) == checkval;
			else if(type == 'end') return val.slice(-checkval.length) == checkval;  
			else return val.indexOf(checkval) > -1;
		}
		if(key_count>0){
			var keyArr = [];
			for(var i = 0; i<key_count; i++){
				if( checkName(localStorage.key(i),name) ) keyArr.push(localStorage.key(i));
			}
			if(keyArr.length>0){
				for(var k in keyArr){ $.removeLocalValue( keyArr[k] ); }
			}
		}
	}
}(jQuery);

//======================Upload=======================
+function($) {
    'use strict';
    var dafaultTemp = '<div><img src="" /></div>';
    var JUploader = function(element, options) {
        this.$element = $(element);
        this.options = $.extend({},
        JUploader.DEFAULTS,options);
        this.options.itemTemp = this.options.itemTemp || dafaultTemp;
        this.init();
    	this.fileList=[];
    };
    JUploader.VERSION = '1.0';
    JUploader.DEFAULTS = {
        readyMessage:"ready", //默认信息
        requestUrl:"",   //图片上传的地址
	    itemTemp:"",     //模板
		itemMax:5,       //同时上传的数据量
        params:{},       //参数
        onDataChange:'', //数据量发生变化时的操作
		onAllComplete:"", //图片全部上传完的操作
		onLoading:'',
		onLoaded:'',
    };

    JUploader.prototype.init = function() {
        this.$temp = this.options.itemTemp.match(/^\#[a-zA-Z0-9_-]/) ? $(this.options.itemTemp).html() : this.options.itemTemp;
        this.data = [];
        this.loadedNum = 0;
        this.errorNum = 0;
        if(typeof this.options.onAllComplete === 'string'){
            try{this.options.onAllComplete = new Function(this.options.onAllComplete);
            }catch(e){console.log('onComplete Event error');}
        }
        if(typeof this.options.onDataChange === 'string'){
            try{this.options.onDataChange = new Function('dataLength','isInRange',this.options.onDataChange);
           	}catch(e){console.log('onComplete Event error');}
        }
    };
    JUploader.prototype.addItem = function(file,thumb) {
        if(this.data.length>=this.options.itemMax){return ;}
        var fileData = {index:-1,xhr:null,thumb:thumb,callMap:{},file:file,isLoading:false,isError:false,
        		isUploaded:false,message:this.options.readyMessage,element:$('<div></div>'),fileName:'未命名',targetRole:this.$element.attr('id')};
        fileData.index = (new Date).getTime();
        fileData.fileName = file.name.substr(0,file.name.lastIndexOf('.'));
        this.data.push(fileData);
        this.updateItemStatus(fileData);
        this.$element.append(fileData.element);
        
        if(typeof this.options.onDataChange === 'function' ){
            this.options.onDataChange.call(this.$element[0],this.data.length,this.data.length<this.options.itemMax);
        }
        if(typeof fileData.callMap.onReady === 'function' ){fileData.callMap.onReady.call(fileData,this);}     
    };
    JUploader.prototype.updateItemStatus = function(fileData){
        if(fileData.element.html() == ''){fileData.element.html( Tpl( this.$temp,fileData));}
    };
    JUploader.prototype.close = function(index){ 
        var data,id,_this = this; 
        for(var i=0;i<this.data.length;i++){if(this.data[i].index == index){data = this.data[i];id = i;break;}} 
        //if(data.isUploaded || data.isLoading){return ;}
		if(!data) return ;
        if(data.xhr){data.xhr.abort();}
        if(data.isError){this.errorNum--;}
        data.element.fadeOut(function(){
        	$(this).remove();
        	_this.data.splice(id,1); 
        	if(typeof _this.options.onDataChange === 'function' ){
	            _this.options.onDataChange.call(_this.$element[0],
	            	_this.data.length,
	            	_this.data.length<_this.options.itemMax);
	        }
        });
        
    };
	JUploader.prototype.abort = function(){
	
        for(var i=0,l=this.data.length;i<l;i++){this.data[i] && this.data[i].xhr.abort();} 
		this.data.length = 0;
		this.loadedNum = 0;
		this.errorNum = 0;
		this.$element.html('');

    };
    JUploader.prototype.traceError = function(fileData,message){
        fileData.isError = true;
        fileData.isLoading = false;
        fileData.isUploaded = false;
        fileData.message = message;
        this.errorNum ++;
        if(typeof fileData.callMap.onError === 'function' ){fileData.callMap.onError.call(fileData,this);}
        this.updateItemStatus(fileData);
    };
    JUploader.prototype.traceSuccess = function(fileData,message){
        fileData.isError = false;
        fileData.isLoading = false;
        fileData.isUploaded = true;
        fileData.message = message;
        if(typeof fileData.callMap.onSuccess === 'function' ){fileData.callMap.onSuccess.call(fileData,this);}
        this.updateItemStatus(fileData);
    };
    JUploader.prototype.traceUploading = function(fileData,message){
        fileData.isError = false;
        fileData.isLoading = true;
        fileData.isUploaded = false;
        fileData.message = message;
        if(typeof fileData.callMap.onPregress === 'function' ){fileData.callMap.onPregress.call(fileData);}
        this.updateItemStatus(fileData);
    };
    JUploader.prototype.sendItem = function(fileData){ 
        if(fileData.isUploaded || fileData.isLoading || fileData.isError) return ;         
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress",$.proxy(function(e){
            var r = e.loaded / e.total;
            var n = isNaN(r) ? 1 : r ;
            fileData.percent = parseInt( n* 100);
            this.traceUploading(fileData, fileData.percent+'%');
        },this));
        xhr.onreadystatechange = $.proxy(function(){
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var result = {};
                    try {
                        result = JSON.parse( xhr.responseText );
                        if(result.code == 200){
                            fileData.serverData = result.data;
                            this.traceSuccess(fileData,'上传成功');
                            this.loadedNum++;
                            if(this.loadedNum == this.data.length && typeof this.options.onAllComplete === 'function'){
                                this.options.onAllComplete.call(this.$element[0]);
                            }
                            return ;
                        }
                        this.traceError(fileData,result.data);
                    } catch(err) {this.traceError(fileData,'JSON解析出错');}
                } else {this.traceError(fileData,'服务器出错');}
            }
        },this);
        var formData = new FormData(),
        params = this.options.params || {};
        params.file = fileData.file;
        for (var key in params) {formData.append(key, params[key]);}
        xhr.open('post', this.options.requestUrl, true);
        xhr.send(formData);
        fileData.xhr = xhr;               
    };
    JUploader.prototype.start = function(callback) {
    	if(callback && typeof callback === 'function') this.options.onAllComplete = callback;
        for( var i=0;i<this.data.length;i++){this.sendItem(this.data[i])}
    };
    JUploader.prototype.onLoading = function() {
    	if (this.options.onLoading && typeof this.options.onLoading === 'string') {
            try { (new Function('' + this.options.onLoading)).call(this.$element[0]);
           	}catch(e){e.name='joye.juploader.error';e.message='onLoading syntax error';throw e;}
        }
    };
    JUploader.prototype.onLoaded = function() {
    	if (this.options.onLoaded && typeof this.options.onLoaded === 'string') {
            try { (new Function('' + this.options.onLoaded)).call(this.$element[0]);
           	}catch(e){e.name='joye.juploader.error';e.message='onLoaded syntax error';throw e;}
        }
    };
    JUploader.prototype.destory = function(){};
    // ========================
    function Plugin(method) {
        var arg = arguments;
        return this.each(function() {
            var $this = $(this);
            var data = $this.data('joye.juploader');
            if (!data) $this.data('joye.juploader', (data = new JUploader(this, $this.data() )));
            if(method === 'close'){data.close(arg[1]);}
            if(method === 'start'){data.start(arg[1]);}
            if(method === 'abort'){data.abort();}
			if(method === 'destory'){data.destory();}
        })
    }
    var old = $.fn.juploader;
    $.fn.juploader = Plugin;
    $.fn.juploader.Constructor = JUploader;
    // ==================
    $.fn.juploader.noConflict = function() {$.fn.juploader = old;return this}
    // ===============
    $(window).on('load',function() {
        $('[role=juploader]').each(function() {
            var $juploader = $(this);
            Plugin.call($juploader, $juploader.data());
        });
        $('body').on('change','[data-button=upload-handler]',function(){
            var instance = $($(this).data('target')).data('joye.juploader');
            instance.onLoading();
			
            var l = this.files.length;
            l = l>instance.options.itemMax ? instance.options.itemMax : l;
			
            instance.fileList = [];
			
            for(var i=0;i<l;i++){              
               (function(myfile){
                    var picReader = new FileReader();
                    instance.fileList.push(picReader);
                    picReader.onloadend = function(evt){ 
                    	var b=true;
                    	instance.addItem(myfile,evt.target.result);
                    	for(var j=0,c=instance.fileList.length;j<c;j++){  
                    		b = b&&(instance.fileList[j].readyState>1);
                    		if(!b) break;
                    	}
                    	if(b){setTimeout(function(){instance.onLoaded();},1000);} //图片全部加载完成后执行
                    }
                    picReader.readAsDataURL(myfile);
               })(this.files[i]);
            }
            this.value="";
        });      
         $('body').on('click','[data-button=upload-handler-trigger]',function(){ 
			
            var instance = $( $($(this).data('target')).data('target')).data('joye.juploader');
            $($(this).data('target')).trigger('click');
            return false;
        })
    });   
} (jQuery);

//=======================PList=======================
+
function($) {
    'use strict';
    // PList author joye used images
    // ==============================
    var PList = function(element, options) {

        this.options = $.extend({},
        PList.DEFAULTS, options);
        this.$element = $(element);
        this.$temp = $(this.options.temp);
        this.$pageTemp = $(this.options.pageTemp);
        this.$pageTempRel = $(this.options.pageContainer);
        this.page = 1;
        this.url = this.options.url;
        this.init();
    }

    PList.VERSION = '1.0';

    PList.DEFAULTS = {
        url: null,
        temp: null,
        done: null,
        doBefore:null,
        error: null,
        nodata:null,
        keepFilter:'',
        appendBy:'',
        pageSize: 9999,
        pageDisplayNum: 5,
        pageAllow: true,
        pageTemp: null,
        pageContainer:null,
        pageKey: 'page',
        pageSizeKey: 'page_size',
        successCondition: 'result.status == 1',
        listDataProperty: 'result.data.data',
        messageDataProperty: 'result.msg',
        totalDataProperty: 'result.data.count',
        appendReadly:'',
        autoLoad:true,
    };

    PList.ERROR = function(message) {
        var error = new Error();
        error.name = 'joye.PList.error';
        error.message = message;
        throw error;
    };

    PList.prototype.init = function() {
        if (!this.options.url) {
            PList.ERROR('url must be not null');
        }

        if (!this.$temp.length) {
            PList.ERROR('invalid temp');
        }
        if (this.options.pageAllow && !this.$pageTemp.length) {
            PList.ERROR('invalid page temp');
        }
        if (this.options.pageAllow && !this.$pageTempRel.length) {
            PList.ERROR('invalid page temprel');
        }
        
        this.options.done = initAttrEvent(this.options.done,function(){
            return new Function("list", "total", "message", "result", this);
        });
        
        this.options.error = initAttrEvent(this.options.error,function(){
            return new Function("message", "result",  this);
        });
        
         this.options.nodata = initAttrEvent(this.options.nodata,function(){
            return new Function(this);
        });

        this.options.appendReadly = initAttrEvent(this.options.appendReadly,function(){
            return new Function("list", "total", "message", "result", this );
        });

        this.options.appendBy = initAttrEvent(this.options.appendBy,function(){
            return new Function("item", this);
        });
        
        this.options.doBefore = initAttrEvent(this.options.doBefore,function(){
            return new Function(this);
        });
        
        if(!this.options.unauto)
			this.load();
    };

    PList.prototype.request = function() {
        var url = (this.url || this.options.url).replace(new RegExp('(&' + this.options.pageKey + '=\\d+)|(&' + this.options.pageSizeKey + '=\\d+)', 'gi'), '');
        var pos = url.charAt(url.length - 1);
        var params = this.options.pageKey + '=' + this.page + '&' + this.options.pageSizeKey + '=' + this.options.pageSize;
        if(url.indexOf(params)>-1) url.replace(params,'');
        if (pos === '?') {
            url = url + '&' + params;
        } else {
            url = url.indexOf('?') > -1 ? (url + '&' + params) : (url + '?' + params);
        }
        return this.url = url;
    };

    PList.prototype.load = function(url,page) {
        var $$ = this;
        if(typeof this.options.doBefore === 'function'){
           this.options.doBefore.call($$.$element[0]);
        }
        this.url = url || this.url;
        this.page = page && !isNaN(page) && page>0 ? page : this.page;
        $.getJSON(this.request(),
        function(result) {
            try { (new Function("result", "if(" + $$.options.successCondition + "){ this.onDone(result," + $$.options.listDataProperty + ",Math.ceil(" + $$.options.totalDataProperty + "/this.options.pageSize)," + $$.options.messageDataProperty + ") }else{ this.onError(result," + $$.options.messageDataProperty + ") }")).call($$, result);
            } catch(e) {
                PList.ERROR(e.message);
            }
        });
    };
	PList.prototype.addRowBefore = function(data){
        this.$element.prepend(       $(Tpl(this.$temp.html(),data))    );   
	};
	PList.prototype.addRowAfter = function(data){
		this.$element.append(       $(Tpl(this.$temp.html(),data))    );  
	};
	PList.prototype.resetRow = function(selector,data){
		this.$element.find(selector).replaceWith(       $(Tpl( this.$temp.html(),data))    );  
	};

	PList.prototype.removeRow = function(selector,speed){

		if(speed == 0){
			this.$element.find(selector).remove();
		}else{
			speed = speed || 200;
			this.$element.find(selector).slideUp(speed,function(){
				$(this).remove();
			});
		}
	};

    PList.prototype.onDone = function(result, list, total, msg) {
        
        var $$ = this;
        
        
        if(typeof this.options.appendReadly === 'function'){
           list = this.options.appendReadly.call($$.$element[0], list,total,msg,result) || list;
        }
            
        this.$element.children().not(this.options.keepFilter).remove();

        $.each(list || [],
        function(i) {
            if (i + 1 > $$.options.pageSize) return;
            this.index = i;
            if(typeof $$.options.appendBy === 'function')
                $$.options.appendBy.call($$.$element[0], Tpl($$.$temp.html(), this) );
            else
                $$.addRowAfter(this);

        });
        this.$pageTempRel.empty();
        if (this.options.pageAllow && total>1) {
            this.$pageTempRel.append(Tpl(this.$pageTemp.html(), this.getPageData(total)));
        }
        var eventType = 'done';

        if (typeof this.options[eventType] === 'function') {
            this.options[eventType].call(this.$element[0], list, total, msg, result);
        }
        if(!list && typeof this.options.nodata === 'function'){
            this.options.nodata.call($$.$element[0]);
        }
        this.tirggerResult(eventType, result);
    };
    PList.prototype.onError = function(result, msg) {
        var eventType = 'error';
        if (typeof this.options[eventType] === 'function') {
            this.options[eventType].call(this.$element[0], msg, result);
        }
        this.tirggerResult(eventType, result);
    };

    PList.prototype.tirggerResult = function(event, result) {
        var evt = $.Event(event + '.joye.PList', result);
        this.$element.trigger(evt);
    };
    PList.prototype.go = function(page) {
//		console.log(page);
        this.page = page;
        this.load();
    };
    PList.prototype.getPageData = function(total) {
        var f = this.page - 1;
        var m = this.options.pageDisplayNum;
        var i = m * Math.floor(f / m);
        var l = i + m;
        var p;
        l = (l <= total ? l: total);
        return {
            element: tracePath(this.$element),
            page: this.page,
            total: total,
            begin: i + 1,
            end: l + 1
        };
    };
    // PList PLUGIN  
    // ========================
    function Plugin(option) {
		var arg= arguments;
        return this.each(function() {
            var $this = $(this);
            var data = $this.data('joye.PList');
            var options = typeof option == 'object' && option;
            if (!data) $this.data('joye.PList', (data = new PList(this, options))) ;
            if (typeof option == 'number') data.go(option);
            else if (option == 'reload') data.load(arg[1],arg[2]);
            else if (option == 'addRowBefore') data.addRowBefore(arg[1]);
			 else if (option == 'addRowAfter') data.addRowAfter(arg[1]);
			  else if (option == 'resetRow') data.resetRow(arg[1],arg[2]);
			  else if (option == 'removeRow') data.removeRow(arg[1],arg[2]);
        })
    }

    var initAttrEvent = function(attrData,callback){
        if (typeof attrData === 'string' && attrData) {
            try {
                return callback.call(attrData);
                
            } catch(e) {
                PList.ERROR('invalid syntax "'+attrData.toString()+'"');
            }
        }

        return false;
    };
    var old = $.fn.plist;
    $.fn.plist = Plugin;
    $.fn.plist.Constructor = PList;
    // PList NO CONFLICT
    // ==================
    $.fn.plist.noConflict = function() {
        $.fn.plist = old;
        return this
    }
    // PList INIT
    // ===============
//  $(window).on('load',
//  function() {
//      $('[role=plist]').each(function() {
//          var $plist = $(this);
//          Plugin.call($plist, $plist.data())
//      })
//  })
} (jQuery);
